package com.lrd.snapshotorder.config.exception;

import com.lrd.snapshotorder.protocol.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultData<String> handleValidException(MethodArgumentNotValidException ex) {
        // 打印日志提示
        log.error("接口服务异常", ex);
        // 处理异常信息
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder errorMsg = new StringBuilder();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMsg.append(fieldError.getDefaultMessage()).append(", ");
        }
        // 去掉最后一个逗号和空格
        errorMsg.delete(errorMsg.length() - 2, errorMsg.length());

        ResultData<String> response = new ResultData<>();
        response.setCode(500);
        response.setMessage(errorMsg.toString());
        // 返回应答数据
        return response;
    }

    @ExceptionHandler(RuntimeException.class)
    public ResultData<String> handleRuntimeException(RuntimeException ex) {
        // 打印日志提示
        log.error("接口服务异常", ex);
        ResultData<String> response = new ResultData<>();
        response.setCode(500);
        response.setMessage(ex.getMessage());
        // 返回应答数据
        return response;
    }
}
